package com.mvc.model;

import java.util.Date;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.mvc.request.ReqCDKeyPage;
import com.mvc.request.ReqCDKeyQPage;

/*激活码*/
public class CDKey extends Model<CDKey> {

	private static final long serialVersionUID = -7703628287803103571L;

	public static enum TableField {
		ID("id", "ID"), NAME("name", "游戏名称"), MAC("mac", "网络地址"), CREATETIME(
				"createTime", "创建时间"), READTIME("readTime", "读取时间"), CODEKEY(
				"codeKey", "激活码"), CONTENT("content", "备注内容"), VIABLESIZE(
				"viableSize", "可使用次数"), USERSIZE("userSize", "已使用次数");

		public String value;
		public String des;

		TableField(String value, String des) {
			this.value = value;
			this.des = des;
		}
	}

	public static final CDKey dao = new CDKey();

	public Page<CDKey> queryPage(ReqCDKeyPage req) {
		StringBuffer formwhere = new StringBuffer("from cdkey where 1=1");

		if (req.getType() == 0) {
			formwhere.append(" and ").append(TableField.VIABLESIZE.value)
					.append(">0");
		} else if (req.getType() == 1) {
			formwhere.append(" and ").append(TableField.VIABLESIZE.value)
					.append("<=0");
		}

		if (StrKit.notBlank(req.getName())) {
			formwhere.append(" and ").append(TableField.NAME.value)
					.append(" like '%").append(req.getName()).append("%'");
			formwhere.append(" or  ").append(TableField.CONTENT.value)
					.append(" like '%").append(req.getName()).append("%'");

		}

		formwhere.append(" order by ").append(TableField.CREATETIME.value)
				.append(" desc");

		return dao.paginate(req.getNowPage(), req.getPageSize(), "select *",
				formwhere.toString());
	}

	public CDKey queryObject(ReqCDKeyQPage req) {
		StringBuffer formwhere = new StringBuffer(
				"select * from cdkey where 1=1 and ");
		formwhere.append(TableField.VIABLESIZE.value).append(">0");

		String search = req.getSearch();

		if (StrKit.notBlank(search)) {
			formwhere.append(" and ").append(TableField.NAME.value)
					.append(" like '%").append(search).append("%'");
			formwhere.append(" or  ").append(TableField.CONTENT.value)
					.append(" like '%").append(search).append("%'");
			formwhere.append(" order by ").append(TableField.CREATETIME.value)
					.append(" asc");
			System.out.println(formwhere.toString());
			CDKey cdKey = dao.findFirst(formwhere.toString());
			if (cdKey != null) {
				cdKey.set(CDKey.TableField.READTIME.value, new Date());
				long size = cdKey.getLong(CDKey.TableField.VIABLESIZE.value) - 1;
				cdKey.set(CDKey.TableField.VIABLESIZE.value, size > 0 ? size: 0);
				
				long userSize = cdKey.getLong(CDKey.TableField.USERSIZE.value) + 1;
				cdKey.set(CDKey.TableField.USERSIZE.value, userSize);
				cdKey.update();
			}
			return cdKey;
		} else {
			return null;
		}
	}
}
